package chapt07.imageload;
// ImageLoad.java
// OpenGL SuperBible
// Demonstrates loading a color image
// Program by Richard S. Wright Jr.

import java.nio.ByteBuffer;
import java.io.IOException;

import javax.media.opengl.GL2;
import javax.media.opengl.glu.GLU;

import com.jogamp.opengl.util.texture.spi.TGAImage;

public class ImageLoad
{
	static GLU glu = new GLU();
	
	//////////////////////////////////////////////////////////////////
	// This function does any needed initialization on the rendering
	// context. 
	protected static void setup(GL2 gl2, int width, int height)
	{
		// Black background
		gl2.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	}
	
	/////////////////////////////////////////////////////////////////
	// Called to draw scene
	protected static void render(GL2 gl2, int w, int h)
	{
		// Prevent a divide by zero, when window is too short
	    // (you cant make a window of zero width).
		if(h == 0)
			h = 1;
		
		gl2.glViewport(0, 0, w, h);
		
		// Reset the coordinate system before modifying
		gl2.glMatrixMode(GL2.GL_PROJECTION);
		gl2.glLoadIdentity();
		
		// Set the clipping volume
		glu.gluOrtho2D(0.0f, (float)w, 0.0, (float)h);
		
		gl2.glMatrixMode(GL2.GL_MODELVIEW);
		gl2.glLoadIdentity();
		
		ByteBuffer pImage = null;
		int iWidth, iHeight;
		int eFormat;
		
		// Clear the window with current clearing color
		gl2.glClear(GL2.GL_COLOR_BUFFER_BIT);
		
		// Targa's are 1 byte aligned
		gl2.glPixelStorei(GL2.GL_UNPACK_ALIGNMENT, 1);
		
		// Load the TGA file, get width, height, and component/format information
		try
		{
			TGAImage tgaImage = TGAImage.read(ImageLoad.class.getResourceAsStream("Fire.tga"));
			iWidth = tgaImage.getWidth();
			iHeight = tgaImage.getHeight();
			eFormat = tgaImage.getGLFormat();
			pImage = tgaImage.getData();
			
			// Use Window coordinates to set raster position
			gl2.glRasterPos2i(0, 0);
			
			// Draw the pixmap
			if(pImage != null)
				gl2.glDrawPixels(iWidth, iHeight, eFormat, GL2.GL_UNSIGNED_BYTE, pImage);
			
			// Don't need the image data anymore
			pImage = null;
		}
		catch(IOException e)
		{
			System.exit(0);
		}
		
		// Do the buffer swap
		gl2.glFlush();
	}
}
